import Http from "axios"
import Cookies from "js-cookie"
import vm from "@/main.js"
import mseSign from "./mseSign"

const mseFormDateHeader = { "x-sdk-content-sha256": "UNSIGNED-PLYLOAD" } // 上传文件 mse网关header带的

const ajax = (config) => {
  if (config.headers["Content-Type"] === "multipart/form-data") {
    Object.assign(config.headers, mseFormDateHeader)
  }
  //**重要 华为云签名 */
  config = mseSign.setMseHeaders(config)

  return new Promise((resolve, reject) => {
    Http(config)
      .then((res) => {
        // 兼容用友，会员的接口
        const result = res.data
        if (result.returnCode || result.resultCode) {
          if (result.returnCode === "0" || result.returnCode === null || result.resultCode === 200) {
            resolve(result.data)
          } else if (result.resultCode === 40105 || result.returnCode === "AUTH-OBTAIN-USER-INFO") {
            // 登录无效
            localStorage.setItem("local-token", "")
            reject({
              errorMsg: "invalid token",
              errorData: {}
            })
          } else {
            //调用失败
            reject({
              errorMsg: result.returnMessage,
              errorData: {}
            })
            vm.$message.warning(result.returnMessage || result.errMsg || result.msg)
          }
        } else if (res.data.code !== undefined) {
          //社区接口
          if (res.data.code == 0) {
            resolve(res.data.data)
          } else if (res.data.code === "10001") {
            // 退出登陆
            localStorage.setItem("local-token", "")
          } else if (res.data.code == "200") {
            //会员的接口
            resolve(res.data.data)
          } else if (res.data.code == "9999" || res.data.code == "9998") {
            //前端要弹校验提示的情况
            resolve(res.data)
          } else if (res.data.code == "4121" && res.config.url.indexOf("recommendation/sortmodel") != -1) {
            //前端要弹校验提示的情况
            resolve(res.data)
          } else {
            vm.$message.warning(res.data.msg)
            reject(res.data)
          }
        } else {
          resolve(res.data)
        }
      })
      .catch((err) => {
        console.log("catch err", err)
        vm.$message.warning("网络错误" + err)
        reject({
          errorMsg: "网络错误",
          errorData: err
        })
      })
  })
}

export const getToken = (() => {
  let _access_Token = ""
  return () => {
    if (_access_Token) return _access_Token
    _access_Token = Cookies.get("token") || ""
    return _access_Token
  }
})()

export default {
  request(baseURL) {
    let host = baseURL
    return (params) => {
      const data = params.opts || {}
      const query = params.query
      let apiParams = {}
      Http.defaults.withCredentials = true
      if (params.contentType) {
        if (params.type == "file") {
          apiParams = {
            headers: { "content-type": params.contentType },
            method: params.method,
            file: true,
            data: params.data
          }
        } else if (params.type == "down") {
          apiParams = {
            headers: { "content-type": params.contentType },
            method: params.method,
            file: true,
            data: params.opts,
            responseType: "blob"
          }
        } else {
          apiParams = {
            headers: { "content-type": params.contentType },
            data: JSON.stringify(params.opts),
            method: params.method
          }
        }
      } else if (params.method === "get") {
        apiParams = {
          params: data,
          method: params.method
        }
      } else if (params.method === "post") {
        if (query) {
          apiParams = {
            headers: { "content-type": "application/json" },
            params: query,
            method: params.method,
            responseType: params.responseType || ""
          }
        } else {
          apiParams = {
            headers: { "content-type": "application/json" },
            data: data,
            method: params.method,
            responseType: params.responseType || ""
          }
        }
      } else {
        apiParams.method = params.method
      }
      apiParams.url = host + params.url.trim()
      getToken() && (apiParams.headers = { ...apiParams.headers, Authorization: `Bearer ${getToken()}` })
      return ajax(apiParams)
    }
  }
}
